<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        const data = [
            {
                id: 0,
                pid: null,
                text: "1"
            },
            {
                id: 1,
                pid: 0,
                text: "1-1"
            },
            {
                id: 2,
                pid: 1,
                text: "1-1-1"
            },
            {
                id: 3,
                pid: 0,
                text: "2"
            },
            {
                id: 4,
                pid: 3,
                text: '2-1'
            },
            {
                id: 5,
                pid: 3,
                text: '2-2'
            }
        ]
        function getTreeList(root, id, list) {
            for (const item of root) {
                if (item.pid === id) {
                    list.push(item)
                }
            }
            for (const item of list) {
                item.children ??= []
                getTreeList(root, item.id, item.children)
                !item.children.length && delete item.children
            }
            return list
        }
        console.log(getTreeList(data, 0, []));

        // flat
        let tree = getTreeList(data, 0, [])
        let result = []
        let tools = [...tree]
        while (tools.length) {
            const current = tools.shift()
            if (Array.isArray(current.children)) {
                tools = [...current.children, ...tools]
                continue
            }
            result.push(current)
        }
        console.log(result);
    </script>
</body>

</html>